import {defineStore} from 'pinia'
import { ref } from 'vue'
import axios from 'axios';

export const useRouterStore = defineStore("router",()=>{
    const isGetterRouter = ref(false)
   
    // 存储从后端获取的菜单信息
    const menuInfoList = ref([]);


    // 从后端获取菜单信息的异步函数
    const getMenuInfoFromBackend = async () => {
        try {
            // 这里假设后端有一个接口 /api/getMenuInfo，根据实际情况修改
            const response = await axios.get('http://localhost:8080/getRoutes?userId=1');
            menuInfoList.value = response.data;
        } catch (error) {
            console.log(error);
        }
    }

     // 将菜单信息转换为路由组件并添加到路由的函数
     const addRoutesFromMenuInfo = () => {
        const routerRoutes = [];

        const addRoutesRecursively = (parentMenuId, menuItems) => {
            menuItems.forEach((menuItem) => {
                const routeConfig = {
                    path: menuItem.menuUrl,
                    name: `route_${menuItem.menuId}`,
                    component: () => import(`@/views/${menuItem.menuUrl.split('/')[1]}/${menuItem.component}.vue`),
                    meta: {
                        menuId: menuItem.menuId,
                        menuName: menuItem.menuName,
                        parentMenuId: parentMenuId
                    }
                };

                routerRoutes.push(routeConfig);

                if (menuItem.children && menuItem.children.length > 0) {
                    addRoutesRecursively(menuItem.menuId, menuItem.children);
                }
            });
        };

        addRoutesRecursively(0, menuInfoList.value);

        return routerRoutes;
    }

    function changeRouter(value){
        isGetterRouter.value = value
    }


    return {
        isGetterRouter,
        menuInfoList,
        getMenuInfoFromBackend,
        addRoutesFromMenuInfo,
        changeRouter
    }
})

// {
//     // 使用persistedstate插件配置持久化
//     persist: {
//         enabled: true,
//         strategies: [
//             {
//                 key: 'router',
//                 storage: localStorage
//             }
//         ]
//     }
// }